﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("开始下载ptpress网站内容");
        int i1 = await DownloadAsync("https://www.baidu.com", "baidu.html"); 
        Console.WriteLine($"下载完成，长度：{i1}");
    }

    // 异步下载并返回内容的长度  
    static async Task<int> DownloadAsync(string url, string destFilePath)
    {
        using (HttpClient httpClient = new HttpClient())
        {
            string body = await httpClient.GetStringAsync(url);
            await File.WriteAllTextAsync(destFilePath, body);
            return body.Length; // 返回下载内容的长度  
        }
    }
}

// 自定义异步方法的线程切换
/*Console.WriteLine("1-Main:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(await CalcAsync(10000));
Console.WriteLine("2-Main:" + Thread.CurrentThread.ManagedThreadId);

static async Task<decimal> CalcAsync(int n)
{
	Console.WriteLine("CalcAsync:" + Thread.CurrentThread.ManagedThreadId);
	decimal result = 1;
	Random rand = new Random();
	for (int i = 0; i < n * n; i++)
	{
		result = result + (decimal)rand.NextDouble();
	}
	return result;
}

//async Task<decimal> CalcAsync(int n)
//{
//    Console.WriteLine("CalcAsync:" + Thread.CurrentThread.ManagedThreadId);
//    return await Task.Run(() => {
//        Console.WriteLine("Task.Run:" + Thread.CurrentThread.ManagedThreadId);
//        decimal result = 1;
//        Random rand = new Random();
//        for (int i = 0; i < n * n; i++)
//        {
//            result = result + (decimal)rand.NextDouble();
//        }
//        return result;
//    });
//}*/

// 库函数线程切换
//Console.WriteLine("1-ThreadId=" + Thread.CurrentThread.ManagedThreadId);
//string str = new string('a', 10000000);
//await File.WriteAllTextAsync("./1.txt", str);
//Console.WriteLine("2-ThreadId=" + Thread.CurrentThread.ManagedThreadId);
//await File.WriteAllTextAsync("./2.txt", str);
//Console.WriteLine("3-ThreadId=" + Thread.CurrentThread.ManagedThreadId);
//File.WriteAllText(path: "./3.txt", contents: str);//同步写入
//Console.WriteLine("4-ThreadId=" + Thread.CurrentThread.ManagedThreadId);


//// 不加async的异步调用：
//string s1 = await ReadFileAsync(1);
//Console.WriteLine(s1);
///*
// // 使用await就要搭配async使用
//async Task<string> ReadFileAsync(int num)
//{
//	switch (num)
//	{
//		case 1:
//			return await File.ReadAllTextAsync("./1.txt");
//		case 2:
//			return await File.ReadAllTextAsync("./2.txt");
//		default:
//			throw new ArgumentException("num invalid");
//	}
//}*/

//// 直接返回Task<string>，没有使用，不需要加async，提高性能
//Task<string> ReadFileAsync(int num)
//{
//    switch (num)
//    {
//        case 1:
//            return File.ReadAllTextAsync("./1.txt");
//        case 2:
//            return File.ReadAllTextAsync("./2.txt");
//        default:
//            throw new ArgumentException("num invalid");
//    }
//}
